package cn.cjx.org.service.impl;

import cn.cjx.basic.service.impl.BaseServiceImpl;
import cn.cjx.basic.utils.MD5Utils;
import cn.cjx.basic.utils.QueryResult;
import cn.cjx.basic.utils.StrUtils;
import cn.cjx.org.domain.Employee;
import cn.cjx.org.mapper.EmployeeMapper;
import cn.cjx.org.query.EmployeeQuery;
import cn.cjx.org.service.IEmployeeService;
import cn.cjx.user.domain.Logininfo;
import cn.cjx.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Description: 员工的service层实现类
 * @Author: cjx
 * @Version: 1.0
 * @Date:  2022/4/19 18:28
 */
@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

	@Autowired
	private EmployeeMapper employeeMapper;

	@Autowired
	private LogininfoMapper logininfoMapper;


	@Override
	public void save(Employee employee) {
		initEmployee(employee);
		Logininfo logininfo = Employee2logininfo(employee);
		logininfoMapper.save(logininfo);
		employee.setLogininfoId(logininfo.getId());
		employeeMapper.save(employee);
		initRelationTable();
	}

	private void initRelationTable() {
		Employee employee = new Employee();
		//删除历史角色
		employeeMapper.removeRoleByEmpId(employee.getId());
		//保存所有角色
		employeeMapper.saveRoleByEmpId(employee.getId(),employee.getRoles());
	}

	private Logininfo Employee2logininfo(Employee employee) {
		Logininfo logininfo = new Logininfo() ;
		BeanUtils.copyProperties(employee,logininfo);
		logininfo.setType(1);
		return logininfo;
	}

	private void initEmployee(Employee employee) {

		String salt = StrUtils.getComplexRandomString(32);
		String md5Pwd = MD5Utils.encrypByMd5(employee.getPassword() + "cjx" + salt + "xxxx");

		employee.setSalt(salt);
		employee.setPassword(md5Pwd);
	}

	@Override
	public void update(Employee employee) {
		super.update(employee);
	}

	@Override
	public void remove(Long id) {
		super.remove(id);
	}

	@Override
	public Employee loadByLogininfoId(Long id) {
		return employeeMapper.loadByLogininfoId(id);
	}

	// 基础的CRUD方法从公共接口继承而来

	// 模块自己特有的方法或者CRUD实现不一样时写在这里
}
